package com.uwo.house.util;

import com.alibaba.fastjson.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 第三方登录辅助类
 * 
 */
public final class ThirdPartyLoginHelper {

	/**
	 * 获取QQ的认证token和用户OpenID
	 * 
	 * @param code
	 * @param host
	 * @return
	 */
	public static final Map<String, String> getQQTokenAndOpenid(String code, String host) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		// 获取令牌
		String tokenUrl = ThirdPartyResources.AccessTokenURLQQ;
		tokenUrl = tokenUrl + "?grant_type=authorization_code&client_id=" + ThirdPartyResources.AppIdQQ
				+ "&client_secret=" + ThirdPartyResources.AppKeyQQ + "&code=" + code
				+ "&redirect_uri=http://" + host + ThirdPartyResources.RedirectUrlQQ;
		String tokenRes = HttpUtil.httpClientPost(tokenUrl);
		if (tokenRes != null && tokenRes.indexOf("access_token") > -1) {
			JSONObject tokenMap = JSONObject.parseObject(tokenRes);
			map.put("access_token", (String)tokenMap.get("access_token"));
			// 获取QQ用户的唯一标识openID
			String openIdUrl = ThirdPartyResources.GetOpenIDURLQQ;
			openIdUrl = openIdUrl + "?access_token=" + tokenMap.get("access_token");
			String openIdRes = HttpUtil.httpClientPost(openIdUrl);
			int i = openIdRes.indexOf("(");
			int j = openIdRes.indexOf(")");
			openIdRes = openIdRes.substring(i + 1, j);
			JSONObject openidObj = JSONObject.parseObject(openIdRes);
			map.put("openId", openidObj.getString("openid"));
		} else {
//          throw new IllegalArgumentException(ThirdPartyResources.getMessage("THIRDPARTY.LOGIN.NOTOKEN", "qq"));
		}
		return map;
	}

	/**
	 * 获取微信的认证token和用户OpenID
	 * 
	 * @param code
	 * @param host
	 * @return
	 */
	public static final Map<String, String> getWxTokenAndOpenid(String code, String host) throws Exception {
		Map<String, String> map = new HashMap<String, String>();
		// 获取令牌
		String tokenUrl = ThirdPartyResources.AccessTokenURLWX;
		tokenUrl = tokenUrl + "?appid=" + ThirdPartyResources.AppIdWX + "&secret="
				+ ThirdPartyResources.AppKeyWX + "&code=" + code + "&grant_type=authorization_code";
		String tokenRes = HttpUtil.httpClientPost(tokenUrl);
		if (tokenRes != null && tokenRes.indexOf("access_token") > -1) {
			JSONObject tokenMap = JSONObject.parseObject(tokenRes);
			map.put("access_token", (String)tokenMap.get("access_token"));
			// 获取微信用户的唯一标识openid
			map.put("openId", (String)tokenMap.get("openid"));
		} else {
//			throw new IllegalArgumentException(ThirdPartyResources.getMessage("THIRDPARTY.LOGIN.NOTOKEN", "weixin"));
		}
		return map;
	}
}
